package com.tengfei.main.system.listener;

import cn.dev33.satoken.secure.BCrypt;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.pinyin.PinyinUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tengfei.common.constant.UserConstants;
import com.tengfei.common.excel.ExcelListener;
import com.tengfei.common.excel.ExcelResult;
import com.tengfei.common.exception.ServiceException;
import com.tengfei.common.utils.ValidatorUtils;
import com.tengfei.common.utils.spring.SpringUtils;
import com.tengfei.main.system.domain.SysDept;
import com.tengfei.main.system.domain.SysUser;
import com.tengfei.main.system.domain.vo.SysUserImportVo;
import com.tengfei.main.system.mapper.SysDeptMapper;
import com.tengfei.main.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * 系统用户自定义导入
 *
 * @author Lion Li
 */
@Slf4j
public class SysUserImportListener extends AnalysisEventListener<SysUserImportVo> implements ExcelListener<SysUserImportVo> {
    private final ISysUserService userService;

    private final String password;


    private int successNum = 0;
    private int failureNum = 0;
    private final StringBuilder successMsg = new StringBuilder();
    private final StringBuilder failureMsg = new StringBuilder();

    public SysUserImportListener() {
        this.userService = SpringUtils.getBean(ISysUserService.class);
        this.password = BCrypt.hashpw(UserConstants.DEFAULT_PWD);
    }

    // TODO 导入用户数据回调
    @Override
    public void invoke(SysUserImportVo userVo, AnalysisContext context) {
        // 姓名转用户名
        if (ObjectUtil.isNull(userVo.getUserName())) {
            userVo.setUserName(PinyinUtil.getPinyin(userVo.getName(), ""));
        }
        SysUser user = userService.selectUserByUserName(userVo.getUserName());
        SysUser userByPhonenumber = userService.selectUserByPhonenumber(userVo.getPhonenumber());
        if (ObjectUtil.isNotNull(userByPhonenumber) &&
                !user.getUserName().equals(userByPhonenumber.getUserName())) {
            failureNum++;
            String msg = "<br/>" + failureNum + "、账号 " + user.getName() + "手机号已被他人注册";
            failureMsg.append(msg);
            return;
        }
        try {
            // 验证是否存在这个用户
            if (ObjectUtil.isNull(user)) {
                user = userVo2Bean(userVo);
                ValidatorUtils.validate(user);
                user.setPassword(password);
                userService.insertUser(user);
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、账号 ").append(user.getName()).append(" 导入成功");
            } else {
                user.setDeptId(getDeptId(userVo.getDeptName()));
                ValidatorUtils.validate(user);
                userService.updateUser(user);
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、账号 ").append(user.getName()).append(" 更新成功");
            }
        } catch (Exception e) {
            failureNum++;
            String msg = "<br/>" + failureNum + "、账号 " + user.getName() + " 导入失败：";
            failureMsg.append(msg).append(e.getMessage());
            log.error(msg, e);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }

    @Override
    public ExcelResult<SysUserImportVo> getExcelResult() {
        return new ExcelResult<SysUserImportVo>() {

            @Override
            public String getAnalysis() {
                if (failureNum > 0) {
                    failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
                    throw new ServiceException(failureMsg.toString());
                } else {
                    successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
                }
                return successMsg.toString();
            }

            @Override
            public List<SysUserImportVo> getList() {
                return null;
            }

            @Override
            public List<String> getErrorList() {
                return null;
            }
        };
    }

    private SysUser userVo2Bean(SysUserImportVo userVo) {
        SysUser user = new SysUser();
        user.setName(userVo.getName());
        user.setUserName(userVo.getUserName());
        user.setPhonenumber(userVo.getPhonenumber());
        user.setSex(userVo.getSex());
        if (ObjectUtil.isNull(userVo.getSex())) {
            userVo.setSex(2);
        }
        // 获取部门
        if (ObjectUtil.isNotNull(userVo)) {
            user.setDeptId(getDeptId(userVo.getDeptName()));
        }
        return user;
    }

    private Long getDeptId(String deptName) {
        SysDeptMapper mapper = SpringUtils.getBean(SysDeptMapper.class);
        List<SysDept> sysDepts = mapper.selectList(new LambdaQueryWrapper<SysDept>()
                .eq(SysDept::getDeptName, deptName)
                .eq(SysDept::getStatus, 1));
        for (SysDept sysDept : sysDepts) {
            return sysDept.getDeptId();
        }
        return null;
    }
}
